package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import com.itheima.service.OrderService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Reference
    private AddressService addressService;
    @Reference
    private OrderService orderService;

    //删除地址
    @RequestMapping("/deleteAddress")
    public Result deleteAddress(Integer id){
        //先判断此地址是否有预约
        try {
            Integer count=orderService.findAddress(id);
            if(count>0){
                //有预约，无法删除
                return new Result(false,MessageConstant.ADDRESS_HAS_ORDER);
            }
            //无预约，删除该地址
            addressService.deleteAddress(id);
            return new Result(true, MessageConstant.DELETE_ADDRESS_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ADDRESS_FAIL);
        }



    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
      return addressService.findPage(queryPageBean);
    }

    //添加地址
    @PostMapping("/add")
    public Result add(@RequestBody Address address) {
        if (address != null) {
            try {
                addressService.addAddress(address);
                return new Result(true, "添加地址成功！");
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "添加地址失败！");
            }
        } else {
            return new Result(false, "该地址无法添加！");
        }
    }
}
